class BlueprintRenderer {
    constructor(container, blueprintSystem) {
        this.container = container;
        this.blueprint = blueprintSystem;

        // 创建画布
        this.canvas = document.createElement('canvas');
        this.ctx = this.canvas.getContext('2d');
        this.container.appendChild(this.canvas);

        // 初始化状态
        this.pan = { x: 0, y: 0 };
        this.zoom = 1;
        this.isPanning = false;
        this.lastMousePos = { x: 0, y: 0 };
        this.connecting = null;
        this.selectedNode = null;
        this.hoveredElement = null;

        // 主题配置
        this.theme = {
            background: '#1E1E1E',
            grid: '#252525',
            nodeBackground: '#2D2D2D',
            nodeHeader: '#1A1A1A',
            nodeBorder: '#3E3E3E',
            nodeTitle: '#E0E0E0',
            pinLabel: '#B0B0B0',
            execPin: '#FFA500',
            dataPin: '#4A4A4A',
            connection: '#FFA500',
            selection: '#4F94FF',
            hoverGlow: 'rgba(79, 148, 255, 0.3)',
            error: '#FF3B30',
            variableNode: '#3A4A6D', // 变量节点基础颜色
            getterNode: '#3D6D3A',  // Get节点颜色
            setterNode: '#6D3A3A',  // Set节点颜色
            simpleGetterNode: '#3A6D6D' // 简单Getter节点颜色
        };
        this.contextMenu = null;
        this.setupContextMenu();
        // 初始化
        this.resize();
        this.setupEventListeners()
        this.setupCanvasControls();
        this.render();
    }

    setupContextMenu() {
        this.contextMenu = document.createElement('div');
        this.contextMenu.className = 'blueprint-context-menu';
        this.contextMenu.style.display = 'none';
        this.contextMenu.innerHTML = `
        <div class="menu-title">Add Node</div>
        <div class="menu-item" data-type="print">Print String</div>
        <div class="menu-item" data-type="branch">Branch</div>
        <div class="menu-item" data-type="delay">Delay</div>
        <div class="menu-item" data-type="math">Math Operation</div>
        <div class="menu-item" data-type="comparison">Comparison</div>
    `;
        this.container.appendChild(this.contextMenu);

        // 添加菜单项点击事件
        this.contextMenu.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const type = e.target.getAttribute('data-type');
                this.addNodeByType(type, this.contextMenuPosition);
                this.hideContextMenu();
            });
        });

        // 点击其他地方隐藏菜单
        document.addEventListener('click', (e) => {
            if (e.target !== this.contextMenu && !this.contextMenu.contains(e.target)) {
                this.hideContextMenu();
            }
        });
    }

// 添加显示/隐藏上下文菜单的方法
    showContextMenu(position) {
        this.contextMenuPosition = this.screenToWorld(position);
        this.contextMenu.style.display = 'block';
        this.contextMenu.style.left = `${position.x}px`;
        this.contextMenu.style.top = `${position.y}px`;
    }

    hideContextMenu() {
        this.contextMenu.style.display = 'none';
    }

// 添加根据类型创建节点的方法
    addNodeByType(type, position) {
        const nodeId = this.blueprint.generateNodeId();
        let newNode;

        switch(type) {
            case 'print':
                newNode = new PrintStringNode(nodeId, position);
                break;
            case 'branch':
                newNode = new BranchNode(nodeId, position);
                break;
            case 'delay':
                newNode = new DelayNode(nodeId, position);
                break;
            case 'math':
                newNode = new MathNode(nodeId, position);
                break;
            case 'comparison':
                newNode = new ComparisonNode(nodeId, position);
                break;
            default:
                return;
        }

        this.blueprint.addNode(newNode);
        this.render();
    }


    // 新增：设置画布控制
    setupCanvasControls() {
        // 获取或创建控制元素
        let controls = this.container.querySelector('.canvas-controls');
        if (!controls) {
            controls = document.createElement('div');
            controls.className = 'canvas-controls';
            controls.innerHTML = `
                <button id="zoom-out">-</button>
                <span class="zoom-display" id="zoom-value">100%</span>
                <button id="zoom-in">+</button>
                <button id="zoom-reset">Reset</button>
            `;
            this.container.appendChild(controls);
        }

        // 获取按钮元素
        this.zoomOutBtn = controls.querySelector('#zoom-out');
        this.zoomInBtn = controls.querySelector('#zoom-in');
        this.zoomResetBtn = controls.querySelector('#zoom-reset');
        this.zoomDisplay = controls.querySelector('#zoom-value');

        // 添加事件监听
        this.zoomOutBtn.addEventListener('click', () => this.zoomCanvas(-0.2));
        this.zoomInBtn.addEventListener('click', () => this.zoomCanvas(0.2));
        this.zoomResetBtn.addEventListener('click', () => this.resetZoom());

        // 初始更新缩放显示
        this.updateZoomDisplay();
    }

    // 新增：缩放画布
    zoomCanvas(zoomDelta) {
        const newZoom = Math.min(Math.max(0.5, this.zoom + zoomDelta), 3);
        if (newZoom !== this.zoom) {
            // 以画布中心为基准缩放
            const center = {
                x: this.canvas.width / 2,
                y: this.canvas.height / 2
            };

            const worldPosBefore = this.screenToWorld(center);
            this.zoom = newZoom;
            const worldPosAfter = this.screenToWorld(center);

            this.pan.x += (worldPosAfter.x - worldPosBefore.x) * this.zoom;
            this.pan.y += (worldPosAfter.y - worldPosBefore.y) * this.zoom;

            this.render();
            this.updateZoomDisplay();
        }
    }

    // 新增：重置缩放
    resetZoom() {
        this.zoom = 1;
        this.pan = { x: 0, y: 0 };
        this.render();
        this.updateZoomDisplay();
    }

    // 新增：更新缩放显示
    updateZoomDisplay() {
        if (this.zoomDisplay) {
            this.zoomDisplay.textContent = `${Math.round(this.zoom * 100)}%`;
        }
    }


    // 调整画布大小
    resize() {
        this.canvas.width = this.container.clientWidth;
        this.canvas.height = this.container.clientHeight;
        this.render();
    }

    // 设置事件监听
    setupEventListeners() {
        this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
        this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
        this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
        this.canvas.addEventListener('wheel', this.handleWheel.bind(this), { passive: false });
        this.canvas.addEventListener('dblclick', this.handleDoubleClick.bind(this));
        this.canvas.addEventListener('mouseleave', this.handleMouseLeave.bind(this));
        window.addEventListener('resize', this.resize.bind(this));
    }

    // 鼠标按下处理
    handleMouseDown(e) {
        if (e.button === 2) { // 右键
            e.preventDefault();
            const mousePos = this.getMousePos(e);
            this.showContextMenu(mousePos);
            return;
        }
        const mousePos = this.getMousePos(e);
        const worldPos = this.screenToWorld(mousePos);

        // 检查是否点击了引脚
        const pinInfo = this.findPinAtPosition(worldPos);
        if (pinInfo) {
            this.startConnection(pinInfo.node, pinInfo.pin, pinInfo.isInput, worldPos);
            return;
        }

        // 检查是否点击了节点
        const node = this.findNodeAtPosition(worldPos);
        if (node) {
            this.selectNode(node, worldPos);
            return;
        }

        // 点击空白区域开始平移
        this.startPanning(mousePos);
    }

    // 鼠标移动处理
    handleMouseMove(e) {
        const mousePos = this.getMousePos(e);
        const worldPos = this.screenToWorld(mousePos);

        // 更新悬停状态
        this.updateHoverState(worldPos);

        // 处理画布平移
        if (this.isPanning) {
            this.handlePanning(mousePos);
            return;
        }

        // 处理节点拖动
        if (this.draggingNode) {
            this.handleNodeDragging(worldPos);
            return;
        }

        // 处理连接线拖动
        if (this.connecting) {
            this.connecting.endPos = worldPos;
            this.render();
        }
    }

    // 鼠标释放处理
    handleMouseUp(e) {
        const mousePos = this.getMousePos(e);
        const worldPos = this.screenToWorld(mousePos);

        // 完成连接
        if (this.connecting) {
            this.finishConnection(worldPos);
        }

        // 重置状态
        this.isPanning = false;
        this.draggingNode = null;
        this.canvas.style.cursor = 'default';
    }

    // 鼠标滚轮缩放处理
    handleWheel(e) {
        e.preventDefault();

        const zoomDelta = -e.deltaY * 0.001;
        const newZoom = Math.min(Math.max(0.5, this.zoom + zoomDelta), 3);

        if (newZoom !== this.zoom) {
            const mousePos = { x: e.clientX, y: e.clientY };
            const worldPosBefore = this.screenToWorld(mousePos);

            this.zoom = newZoom;

            const worldPosAfter = this.screenToWorld(mousePos);
            this.pan.x += mousePos.x - worldPosAfter.x * this.zoom;
            this.pan.y += mousePos.y - worldPosAfter.y * this.zoom;

            this.render();
            this.updateZoomDisplay(); // 新增：更新缩放显示
        }
    }


    // 双击处理
    handleDoubleClick(e) {
        const mousePos = this.getMousePos(e);
        const worldPos = this.screenToWorld(mousePos);

        // 在双击位置添加新节点
        const newNodeId = this.blueprint.generateNodeId();
        const newNode = new PrintStringNode(newNodeId, worldPos);
        this.blueprint.addNode(newNode);
        this.render();
    }

    // 鼠标离开画布
    handleMouseLeave() {
        this.isPanning = false;
        this.draggingNode = null;
        this.canvas.style.cursor = 'default';
    }



    render() {
        if (this.animationFrameId) {
            cancelAnimationFrame(this.animationFrameId);
        }
        this.animationFrameId = requestAnimationFrame(() => {
            // 实际的渲染逻辑
            this._render();
            this.animationFrameId = null;
        });
    }
    // 渲染函数
    _render() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        // 应用变换
        this.ctx.save();
        this.ctx.translate(this.pan.x, this.pan.y);
        this.ctx.scale(this.zoom, this.zoom);

        // 绘制背景和网格
        this.drawBackground();
        this.drawGrid();

        // 绘制连接线
        this.drawConnections();

        // 绘制节点
        this.drawNodes();

        // 绘制临时连接线
        if (this.connecting) {
            this.drawTemporaryConnection();
        }

        this.ctx.restore();
    }

    // 以下是辅助方法实现
    // ==============================================

    // 获取鼠标位置（相对于画布）
    getMousePos(e) {
        const rect = this.canvas.getBoundingClientRect();
        return {
            x: e.clientX - rect.left,
            y: e.clientY - rect.top
        };
    }

    // 屏幕坐标转世界坐标
    screenToWorld(screenPos) {
        return {
            x: (screenPos.x - this.pan.x) / this.zoom,
            y: (screenPos.y - this.pan.y) / this.zoom
        };
    }

    // 世界坐标转屏幕坐标
    worldToScreen(worldPos) {
        return {
            x: worldPos.x * this.zoom + this.pan.x,
            y: worldPos.y * this.zoom + this.pan.y
        };
    }

    // 查找指定位置的节点
    findNodeAtPosition(pos) {
        return this.blueprint.nodes.find(node =>
            pos.x >= node.position.x &&
            pos.x <= node.position.x + node.width &&
            pos.y >= node.position.y &&
            pos.y <= node.position.y + node.height
        );
    }

    // 查找指定位置的引脚
    findPinAtPosition(pos) {
        for (const node of this.blueprint.nodes) {
            // 检查输入引脚
            for (let i = 0; i < node.inputPins.length; i++) {
                const pin = node.inputPins[i];
                const pinPos = {
                    x: node.position.x - 8,
                    y: node.position.y + 45 + i * 20
                };

                if (this.distance(pos, pinPos) < 10) {
                    return { node, pin, isInput: true };
                }
            }

            // 检查输出引脚
            for (let i = 0; i < node.outputPins.length; i++) {
                const pin = node.outputPins[i];
                const pinPos = {
                    x: node.position.x + node.width + 8,
                    y: node.position.y + 45 + i * 20
                };

                if (this.distance(pos, pinPos) < 10) {
                    return { node, pin, isInput: false };
                }
            }
        }
        return null;
    }

    // 计算两点间距离
    distance(a, b) {
        return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
    }

    // 开始创建连接
    startConnection(node, pin, isInput, startPos) {
        this.connecting = {
            node,
            pin,
            isInput,
            startPos: {
                x: isInput ? node.position.x - 8 : node.position.x + node.width + 8,
                y: node.position.y + 45 + (isInput ?
                    node.inputPins.indexOf(pin) :
                    node.outputPins.indexOf(pin)) * 20
            },
            endPos: startPos
        };
        this.canvas.style.cursor = 'crosshair';
    }

    // 完成连接
    finishConnection(endPos) {
        const endPinInfo = this.findPinAtPosition(endPos);

        if (endPinInfo && endPinInfo.isInput !== this.connecting.isInput) {
            if (this.connecting.isInput) {
                // 输入 -> 输出连接
                this.blueprint.addConnection(
                    endPinInfo.node.id,
                    endPinInfo.pin.name,
                    this.connecting.node.id,
                    this.connecting.pin.name
                );
            } else {
                // 输出 -> 输入连接
                this.blueprint.addConnection(
                    this.connecting.node.id,
                    this.connecting.pin.name,
                    endPinInfo.node.id,
                    endPinInfo.pin.name
                );
            }
        }

        this.connecting = null;
        this.render();
    }

    // 开始平移画布
    startPanning(mousePos) {
        this.isPanning = true;
        this.lastMousePos = mousePos;
        this.canvas.style.cursor = 'grabbing';
    }

    // 处理画布平移
    handlePanning(mousePos) {
        const dx = mousePos.x - this.lastMousePos.x;
        const dy = mousePos.y - this.lastMousePos.y;

        this.pan.x += dx;
        this.pan.y += dy;
        this.lastMousePos = mousePos;

        this.render();
    }

    // 选择节点
    selectNode(node, clickPos) {
        // 清除之前的选择
        if (this.selectedNode) {
            this.selectedNode.isSelected = false;
        }

        // 设置新选择
        this.selectedNode = node;
        node.isSelected = true;

        // 准备拖动
        this.draggingNode = {
            node,
            offsetX: clickPos.x - node.position.x,
            offsetY: clickPos.y - node.position.y
        };

        this.canvas.style.cursor = 'move';
        this.render();
    }

    // 处理节点拖动
    handleNodeDragging(worldPos) {
        this.draggingNode.node.position.x = worldPos.x - this.draggingNode.offsetX;
        this.draggingNode.node.position.y = worldPos.y - this.draggingNode.offsetY;
        this.render();
    }

    // 更新悬停状态
    updateHoverState(worldPos) {
        const prevHovered = this.hoveredElement;
        this.hoveredElement = null;

        // 检查悬停在节点上
        const node = this.findNodeAtPosition(worldPos);
        if (node) {
            // 检查悬停在引脚上
            const pin = this.findPinAtPosition(worldPos);
            if (pin) {
                this.hoveredElement = { type: 'pin', ...pin };
                this.canvas.style.cursor = 'pointer';
            } else {
                this.hoveredElement = { type: 'node', node };
                this.canvas.style.cursor = 'move';
            }
        } else {
            this.canvas.style.cursor = 'default';
        }

        // 如果悬停状态改变，重新渲染
        if ((prevHovered?.type !== this.hoveredElement?.type) ||
            (prevHovered?.node?.id !== this.hoveredElement?.node?.id)) {
            this.render();
        }
    }

    // 绘制背景
    drawBackground() {
        this.ctx.fillStyle = this.theme.background;
        this.ctx.fillRect(
            -this.pan.x / this.zoom,
            -this.pan.y / this.zoom,
            this.canvas.width / this.zoom,
            this.canvas.height / this.zoom
        );
    }

    // 绘制网格
    drawGrid() {
        const gridSize = 20 * this.zoom;
        const offsetX = this.pan.x % gridSize;
        const offsetY = this.pan.y % gridSize;

        // 计算可见区域
        const visibleStartX = -this.pan.x / this.zoom;
        const visibleStartY = -this.pan.y / this.zoom;
        const visibleEndX = visibleStartX + this.canvas.width / this.zoom;
        const visibleEndY = visibleStartY + this.canvas.height / this.zoom;

        // 计算网格线范围
        const startX = Math.floor(visibleStartX / gridSize) * gridSize;
        const startY = Math.floor(visibleStartY / gridSize) * gridSize;
        const endX = Math.ceil(visibleEndX / gridSize) * gridSize;
        const endY = Math.ceil(visibleEndY / gridSize) * gridSize;

        this.ctx.strokeStyle = this.theme.grid;
        this.ctx.lineWidth = 1;

        // 绘制垂直线
        for (let x = startX; x <= endX; x += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, startY);
            this.ctx.lineTo(x, endY);
            this.ctx.stroke();
        }

        // 绘制水平线
        for (let y = startY; y <= endY; y += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(startX, y);
            this.ctx.lineTo(endX, y);
            this.ctx.stroke();
        }
    }

    // 绘制节点
    drawNodes() {
        // 按Y坐标排序确保正确重叠顺序
        const sortedNodes = [...this.blueprint.nodes].sort((a, b) => a.position.y - b.position.y);

        sortedNodes.forEach(node => {
            this.drawNode(node);
        });
    }

    // 绘制单个节点
    drawNode(node) {
        this.ctx.save();
        this.ctx.translate(node.position.x, node.position.y);

        // 绘制阴影
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
        this.ctx.shadowBlur = 10;
        this.ctx.shadowOffsetY = 3;

        // 绘制节点主体
        this.drawNodeBody(node);

        // 绘制标题栏
        this.drawNodeHeader(node);

        // 绘制引脚
        this.drawNodePins(node);

        // 绘制选中状态
        if (node.isSelected) {
            this.drawNodeSelection(node);
        }

        // 绘制悬停效果
        if (this.hoveredElement?.node?.id === node.id &&
            this.hoveredElement.type === 'node') {
            this.drawNodeHoverEffect(node);
        }

        this.ctx.restore();
    }

    // 绘制节点主体
    drawNodeBody(node) {
        this.ctx.fillStyle = this.theme.nodeBackground;
        this.ctx.strokeStyle = this.theme.nodeBorder;
        this.ctx.lineWidth = 2;

        this.roundRect(0, 0, node.width, node.height, 4);
        this.ctx.fill();
        this.ctx.stroke();
    }

    // 绘制节点标题栏
    drawNodeHeader(node) {
        // 为变量节点设置不同的背景色
        if (node.nodeType === "variable") {
            if (node.nodeSubType === "getter") {
                this.ctx.fillStyle = this.theme.getterNode;
            } else if (node.nodeSubType === "setter") {
                this.ctx.fillStyle = this.theme.setterNode;
            } else if (node.nodeSubType === "simple-getter") {
                this.ctx.fillStyle = this.theme.simpleGetterNode;
            } else {
                this.ctx.fillStyle = this.theme.variableNode;
            }
        } else {
            this.ctx.fillStyle = this.theme.nodeHeader;
        }

        this.roundRect(0, 0, node.width, 30, [4, 4, 0, 0]);
        this.ctx.fill();

        // 节点标题
        this.ctx.fillStyle = this.theme.nodeTitle;
        this.ctx.font = 'bold 12px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';

        // 处理长标题的换行
        const maxWidth = node.width - 20;
        const lines = this.wrapText(node.title, maxWidth);

        lines.forEach((line, i) => {
            this.ctx.fillText(line, node.width / 2, 15 + (i * 14));
        });
    }

    wrapText(text, maxWidth) {
        const words = text.split(' ');
        const lines = [];
        let currentLine = words[0];

        for (let i = 1; i < words.length; i++) {
            const word = words[i];
            const width = this.ctx.measureText(currentLine + ' ' + word).width;
            if (width < maxWidth) {
                currentLine += ' ' + word;
            } else {
                lines.push(currentLine);
                currentLine = word;
            }
        }
        lines.push(currentLine);
        return lines;
    }


    // 绘制节点引脚
    drawNodePins(node){
        if (node instanceof VariableGetterNode) {
            // 更紧凑的绘制方式
            node.outputPins.forEach((pin, index) => {
                const pinY = 30 + index * 20; // 更靠近顶部
                const pinX = node.width + 8;

                this.ctx.fillStyle = this.theme.dataPin;
                this.ctx.beginPath();
                this.ctx.arc(pinX, pinY, 5, 0, Math.PI * 2);
                this.ctx.fill();

                // 引脚标签
                this.ctx.fillStyle = this.theme.pinLabel;
                this.ctx.font = '10px Arial'; // 更小的字体
                this.ctx.textAlign = 'left';
                this.ctx.textBaseline = 'middle';
                this.ctx.fillText(pin.name, node.width + 15, pinY); // 更紧凑的间距
            });
            return;
        }
        // 输入引脚
        node.inputPins.forEach((pin, index) => {
            const pinY = 45 + index * 20;
            const isExec = pin.type === 'exec';

            // 执行引脚使用三角形，数据引脚使用圆形
            if (isExec) {
                // 执行引脚 - 三角形 (向左)
                const pinX = -6;
                this.ctx.fillStyle = this.theme.execPin;
                this.ctx.beginPath();
                this.ctx.moveTo(pinX, pinY);
                this.ctx.lineTo(pinX - 12, pinY - 6);
                this.ctx.lineTo(pinX - 12, pinY + 6);
                this.ctx.closePath();
                this.ctx.fill();
            } else {
                // 数据引脚 - 圆形
                const pinX = -8;
                this.ctx.fillStyle = this.theme.dataPin;
                this.ctx.beginPath();
                this.ctx.arc(pinX, pinY, 5, 0, Math.PI * 2);
                this.ctx.fill();
            }

            // 引脚标签
            this.ctx.fillStyle = this.theme.pinLabel;
            this.ctx.font = '12px Arial';
            this.ctx.textAlign = 'right';
            this.ctx.textBaseline = 'middle';
            this.ctx.fillText(pin.name, -20, pinY);

            // 悬停效果
            if (this.hoveredElement?.type === 'pin' &&
                this.hoveredElement.node.id === node.id &&
                this.hoveredElement.pin.name === pin.name) {
                this.drawPinHoverEffect(isExec ? -6 : -8, pinY);
            }
        });

        // 输出引脚
        node.outputPins.forEach((pin, index) => {
            const pinY = 45 + index * 20;
            const isExec = pin.type === 'exec';

            // 执行引脚使用三角形，数据引脚使用圆形
            if (isExec) {
                // 执行引脚 - 三角形 (向右)
                const pinX = node.width + 6;
                this.ctx.fillStyle = this.theme.execPin;
                this.ctx.beginPath();
                this.ctx.moveTo(pinX, pinY);
                this.ctx.lineTo(pinX + 12, pinY - 6);
                this.ctx.lineTo(pinX + 12, pinY + 6);
                this.ctx.closePath();
                this.ctx.fill();
            } else {
                // 数据引脚 - 圆形
                const pinX = node.width + 8;
                this.ctx.fillStyle = this.theme.dataPin;
                this.ctx.beginPath();
                this.ctx.arc(pinX, pinY, 5, 0, Math.PI * 2);
                this.ctx.fill();
            }

            // 引脚标签
            this.ctx.fillStyle = this.theme.pinLabel;
            this.ctx.font = '12px Arial';
            this.ctx.textAlign = 'left';
            this.ctx.textBaseline = 'middle';
            this.ctx.fillText(pin.name, node.width + 20, pinY);

            // 悬停效果
            if (this.hoveredElement?.type === 'pin' &&
                this.hoveredElement.node.id === node.id &&
                this.hoveredElement.pin.name === pin.name) {
                this.drawPinHoverEffect(isExec ? node.width + 6 : node.width + 8, pinY);
            }
        });
    }
    // 绘制节点选中状态
    drawNodeSelection(node) {
        this.ctx.strokeStyle = this.theme.selection;
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 3]);
        this.roundRect(-4, -4, node.width + 8, node.height + 8, 6);
        this.ctx.stroke();
        this.ctx.setLineDash([]);
    }

    // 绘制节点悬停效果
    drawNodeHoverEffect(node) {
        this.ctx.fillStyle = this.theme.hoverGlow;
        this.roundRect(-2, -2, node.width + 4, node.height + 4, 5);
        this.ctx.fill();
    }

    // 更新引脚悬停效果
    drawPinHoverEffect(x, y) {
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
        this.ctx.beginPath();
        this.ctx.arc(x, y, 12, 0, Math.PI * 2);
        this.ctx.fill();
    }

    // 绘制连接线
    drawConnections() {
        this.ctx.lineWidth = 2;
        this.ctx.lineCap = 'round';

        this.blueprint.connections.forEach(connection => {
            this.drawConnection(connection);
        });
    }

    // 绘制单个连接线
    drawConnection(connection) {
        const sourceNode = this.blueprint.getNode(connection.sourceNode);
        const targetNode = this.blueprint.getNode(connection.targetNode);

        if (!sourceNode || !targetNode) return;

        const sourcePin = sourceNode.outputPins.find(p => p.name === connection.sourcePin);
        const targetPin = targetNode.inputPins.find(p => p.name === connection.targetPin);

        if (!sourcePin || !targetPin) return;

        // 计算引脚位置
        const sourcePos = this.getPinPosition(sourceNode, connection.sourcePin, false);
        const targetPos = this.getPinPosition(targetNode, connection.targetPin, true);

        if (!sourcePos || !targetPos) return;

        // 设置连接线样式
        this.ctx.strokeStyle = sourcePin.type === 'exec' ?
            this.theme.execPin : this.theme.dataPin;
        this.ctx.lineWidth = sourcePin.type === 'exec' ? 3 : 2;

        // 绘制贝塞尔曲线
        this.drawBezierConnection(sourcePos, targetPos);
    }

// 更新引脚位置计算的相关方法
    getPinPosition(node, pinName, isInput) {
        const pins = isInput ? node.inputPins : node.outputPins;
        const pinIndex = pins.findIndex(p => p.name === pinName);
        if (pinIndex === -1) return null;

        const isExec = pins.find(p => p.name === pinName)?.type === 'exec';
        const x = isInput ?
            (isExec ? node.position.x - 6 : node.position.x - 8) :
            (isExec ? node.position.x + node.width + 6 : node.position.x + node.width + 8);
        const y = node.position.y + 45 + pinIndex * 20;

        return { x, y };
    }

    // 绘制贝塞尔曲线连接
    drawBezierConnection(start, end) {
        const cp1x = start.x + Math.max(50, Math.abs(end.x - start.x) * 0.5);
        const cp1y = start.y;
        const cp2x = end.x - Math.max(50, Math.abs(end.x - start.x) * 0.5);
        const cp2y = end.y;

        this.ctx.beginPath();
        this.ctx.moveTo(start.x, start.y);
        this.ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, end.x, end.y);
        this.ctx.stroke();

        // 绘制箭头
        this.drawArrow(end.x, end.y, Math.atan2(end.y - cp2y, end.x - cp2x));
    }

    // 绘制箭头
    drawArrow(x, y, angle) {
        const length = 10;
        this.ctx.save();
        this.ctx.translate(x, y);
        this.ctx.rotate(angle);

        this.ctx.beginPath();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(-length, -length/2);
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(-length, length/2);
        this.ctx.stroke();

        this.ctx.restore();
    }

    // 绘制临时连接线
    drawTemporaryConnection() {
        const startPos = this.connecting.startPos;
        const endPos = this.connecting.endPos;

        this.ctx.strokeStyle = this.connecting.pin.type === 'exec' ?
            this.theme.execPin : this.theme.dataPin;
        this.ctx.lineWidth = this.connecting.pin.type === 'exec' ? 3 : 2;

        this.drawBezierConnection(startPos, endPos);
    }

    // 绘制圆角矩形
    roundRect(x, y, width, height, radius) {
        if (typeof radius === 'number') {
            radius = { tl: radius, tr: radius, br: radius, bl: radius };
        } else {
            radius = { tl: radius[0], tr: radius[1], br: radius[2], bl: radius[3] };
        }

        this.ctx.beginPath();
        this.ctx.moveTo(x + radius.tl, y);
        this.ctx.lineTo(x + width - radius.tr, y);
        this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
        this.ctx.lineTo(x + width, y + height - radius.br);
        this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
        this.ctx.lineTo(x + radius.bl, y + height);
        this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
        this.ctx.lineTo(x, y + radius.tl);
        this.ctx.quadraticCurveTo(x, y, x + radius.tl, y);
        this.ctx.closePath();
    }

    getLastMousePosition() {
        return this.lastMousePos;
    }
}
